import { query2 } from "../../mysqlQuery.js";
import Joi from "joi";
import { getRandomId } from "../../common/index.js";
import SDTime from "silly-datetime"; //时间格式化处理插件
//查询用户列表
function webQueryUser(req, res, next) {
  query2([
    {
      sql: "select * from user limit ?,?;",
      values: [req.body.pageNum * req.body.pageSize, req.body.pageSize],
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg:"查询成功",
        data: out[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//新增用户
function webAddUser(req, res, next) {
  // const schema = Joi.object().keys({
  //   user_name: Joi.string().min(1).max(7).required(),
  // });
  // const result = Joi.validate(req.body, schema, { allowUnknown: true });
  // if (result.error != null) {
  //   next(result.error);
  //   return;
  // }
  query2([
    {
      sql: "select * from user where user_name=?",
      values: [req.body.user_name],
    },
  ])
    .then((out) => {
      if (out[0].rows.length > 0) {
        res.send({
          code: 400,
          msg: "用户名已存在，请重新取名！",
          data: [],
        });
      } else {
        query2([
          {
            sql: "insert into user (user_id,user_name,sex,create_time) values (?,?,?,?)",
            values: [
              getRandomId(8),
              req.body.user_name,
              req.body.sex,
              SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
            ],
          },
        ])
          .then((end) => {
            res.send({
              code: 200,
              msg: "注册成功！",
              data: end[0].rows,
            });
          })
          .catch((err) => {
            next(err);
          });
      }
    })
    .catch((err) => {
      next(err);
    });
}
//删除用户
function webLoseUser(req, res, next) {
  const schema = Joi.object().keys({
    user_ids: Joi.string().required(),
  });
  const result = Joi.validate(req.query, schema, {
    allowUnknown: true,
  });
  if (result.error != null) {
    next(result.error);
    return;
  }
  let userIdArr = req.query.user_ids.split(",");
  let sql = "",
    values = [];
  userIdArr.forEach((element) => {
    sql += `delete from user where user_id=${element};`;
    values.push(element);
  });
  query2([
    {
      sql,
      values,
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg: "删除成功！",
        data: out,
      });
    })
    .catch((err) => {
      next(err);
    });
}
export { webAddUser, webLoseUser,webQueryUser };
